﻿using RxxAdmin.IServices;
using RxxAdmin.Model.Entity;
using RxxAdmin.Model.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RxxAdmin.Services;

public class SysMenuService : BaseServices<SysMenu>, ISysMenuService
{
    public SysMenuService()
    {
        
    }
    public async Task<List<SysMenu>> MenuTreeList(SysMenuIn input)
    {
        if (string.IsNullOrEmpty(input.MenuTitle) || string.IsNullOrWhiteSpace(input.MenuTitle))
        {
            input.MenuTitle = "";
        }
        //获取所有的菜单权限
        var menusall = await base.Query();
        var menusroot = (await base.Query()).Where(d => d.ParentId == 0).OrderBy(d => d.MenuSort).ToList();
        List<SysMenu> menus = ConvertMenuTree(menusall, menusroot);
        var res = new List<SysMenu>();
        foreach (var item in menus)
        {
            res.Add(ConvertMenu(item));
        }
        return res;
    }

    private List<SysMenu> ConvertMenuTree(List<SysMenu> menusall, List<SysMenu> menusroot) {
        foreach (var item in menusroot)
        {
            var childs = menusall.Where(d => d.ParentId == item.Id).OrderBy(d => d.MenuSort);
            if (childs.Count() > 0)
            {
                item.Children = childs.ToList();
                ConvertMenuTree(menusall, item.Children);
            }            
        }
        return menusroot;
    }

    /// <summary>
    /// 私有方法，转化前端路由
    /// </summary>
    /// <param name="menu"></param>
    /// <returns></returns>
    private SysMenu ConvertMenu(SysMenu menu)
    {
        menu.Component = menu.RoutePath + "/index";
        menu.Children = menu.Children?.Select(ConvertMenu).ToList();
        return menu;
    }
}
